// 服务商模拟数据
import {
  type ServiceProviderChannelConfig
} from './channel-config-templates'
import { paymentChannels } from './channels'
import { protocol3Manager } from './protocol3-manager'

export interface ServiceProvider {
  id: number
  providerId: string
  providerName: string
  providerType: 'PAYMENT' | 'TECH' | 'INTEGRATED'
  contactPerson: string
  contactPhone: string
  contactEmail: string
  merchantCount: number
  channelConfigs: ServiceProviderChannelConfig[]
  status: number
  createdTime: string
}

export const serviceProviders: ServiceProvider[] = [
  {
    id: 1,
    providerId: 'SP1752154718336',
    providerName: '火金科技服务商',
    providerType: 'PAYMENT',
    contactPerson: '张三',
    contactPhone: '13800138000',
    contactEmail: 'zhangsan@shouyin.com',
    merchantCount: 120,
    channelConfigs: [
      {
        id: 'SPCC1752154718336001',
        providerId: 'SP1752154718336',
        channelId: 'CH0001',
        channelName: '微信支付',
        enabled: true,
        configData: {
          basic: {
            appId: 'wx1234567890123456',
            mchId: '1234567890',
            apiKey: 'abcdefghijklmnopqrstuvwxyz123456',
            apiVersion: 'v3'
          },
          advanced: {
            notifyUrl: 'https://api.huojin.com/notify/wechat',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-15 10:30:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-01 10:00:00',
        updatedTime: '2024-01-15 10:30:00'
      },
      {
        id: 'SPCC1752154718336002',
        providerId: 'SP1752154718336',
        channelId: 'CH0002',
        channelName: '支付宝',
        enabled: true,
        configData: {
          basic: {
            appId: '2021001234567890',
            pid: '2088123456789012',
            signType: 'RSA2'
          },
          security: {
            privateKey: '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA7qWnznuIgMrSUFJkpHTC4Q8w...',
            publicKey: '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...'
          },
          advanced: {
            notifyUrl: 'https://api.huojin.com/notify/alipay',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-15 09:20:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-01 10:00:00',
        updatedTime: '2024-01-15 09:20:00'
      },
      {
        id: 'SPCC1752154718336003',
        providerId: 'SP1752154718336',
        channelId: 'CH0003',
        channelName: '汇付天下',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'HF1234567890'
          },
          security: {
            apiKey: 'hf_api_key_123456789012345678901234',
            secretKey: 'hf_secret_key_123456789012345678901234'
          },
          advanced: {
            notifyUrl: 'https://api.huojin.com/notify/huifu',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-14 16:45:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-01 10:00:00',
        updatedTime: '2024-01-14 16:45:00'
      },
      {
        id: 'SPCC1752154718336004',
        providerId: 'SP1752154718336',
        channelId: 'CH0004',
        channelName: '斗拱支付',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'DG1234567890'
          },
          security: {
            apiKey: 'dg_api_key_123456789012345678901234',
            secretKey: 'dg_secret_key_123456789012345678901234'
          },
          advanced: {
            notifyUrl: 'https://api.huojin.com/notify/dougong',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-14 11:30:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-01 10:00:00',
        updatedTime: '2024-01-14 11:30:00'
      },
      {
        id: 'SPCC1752154718336005',
        providerId: 'SP1752154718336',
        channelId: 'CH0005',
        channelName: '富友支付',
        enabled: false,
        configData: {
          basic: {
            merchantId: 'FY1234567890'
          },
          security: {
            apiKey: 'fy_api_key_123456789012345678901234',
            secretKey: 'fy_secret_key_123456789012345678901234'
          },
          advanced: {
            notifyUrl: 'https://api.huojin.com/notify/fuiou',
            sandboxMode: 'false'
          }
        },
        status: 'INACTIVE',
        createdTime: '2024-01-01 10:00:00',
        updatedTime: '2024-01-01 10:00:00'
      },
      {
        id: 'SPCC1752154718336006',
        providerId: 'SP1752154718336',
        channelId: 'CH0006',
        channelName: '拉卡拉',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'LKL1234567890'
          },
          security: {
            apiKey: 'lkl_api_key_123456789012345678901234',
            secretKey: 'lkl_secret_key_123456789012345678901234'
          },
          advanced: {
            notifyUrl: 'https://api.huojin.com/notify/lakala',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-13 14:20:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-01 10:00:00',
        updatedTime: '2024-01-13 14:20:00'
      },
      {
        id: 'SPCC1752154718336007',
        providerId: 'SP1752154718336',
        channelId: 'CH0007',
        channelName: '乐刷支付',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'LS1234567890'
          },
          security: {
            apiKey: 'ls_api_key_123456789012345678901234',
            secretKey: 'ls_secret_key_123456789012345678901234'
          },
          advanced: {
            notifyUrl: 'https://api.huojin.com/notify/leshua',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-15 16:30:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-01 10:00:00',
        updatedTime: '2024-01-15 16:30:00'
      }
    ],
    status: 1,
    createdTime: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    providerId: 'SP1752154718337',
    providerName: '田园网络服务商',
    providerType: 'PAYMENT',
    contactPerson: '李四',
    contactPhone: '13900139000',
    contactEmail: 'lisi@shouyin.com',
    merchantCount: 85,
    channelConfigs: [
      {
        id: 'SPCC1752154718337001',
        providerId: 'SP1752154718337',
        channelId: 'CH0001',
        channelName: '微信支付',
        enabled: true,
        configData: {
          basic: {
            appId: 'wx9876543210987654',
            mchId: '9876543210',
            apiKey: 'zyxwvutsrqponmlkjihgfedcba987654',
            apiVersion: 'v3'
          },
          advanced: {
            notifyUrl: 'https://api.tianyuan.com/notify/wechat',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-14 11:30:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-02 10:00:00',
        updatedTime: '2024-01-14 11:30:00'
      },
      {
        id: 'SPCC1752154718337002',
        providerId: 'SP1752154718337',
        channelId: 'CH0002',
        channelName: '支付宝',
        enabled: true,
        configData: {
          basic: {
            appId: '2021001234567891',
            pid: '2088123456789013',
            signType: 'RSA2'
          },
          security: {
            privateKey: '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA7qWnznuIgMrSUFJkpHTC4Q8w...',
            publicKey: '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...'
          },
          advanced: {
            notifyUrl: 'https://api.tianyuan.com/notify/alipay',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-14 15:20:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-02 10:00:00',
        updatedTime: '2024-01-14 15:20:00'
      },
      {
        id: 'SPCC1752154718337003',
        providerId: 'SP1752154718337',
        channelId: 'CH0003',
        channelName: '汇付天下',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'HF9876543210'
          },
          security: {
            apiKey: 'hf_api_key_987654321098765432109876',
            secretKey: 'hf_secret_key_987654321098765432109876'
          },
          advanced: {
            notifyUrl: 'https://api.tianyuan.com/notify/huifu',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-13 09:45:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-02 10:00:00',
        updatedTime: '2024-01-13 09:45:00'
      },
      {
        id: 'SPCC1752154718337004',
        providerId: 'SP1752154718337',
        channelId: 'CH0005',
        channelName: '富友支付',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'FY9876543210'
          },
          security: {
            apiKey: 'fy_api_key_987654321098765432109876',
            secretKey: 'fy_secret_key_987654321098765432109876'
          },
          advanced: {
            notifyUrl: 'https://api.tianyuan.com/notify/fuiou',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-15 14:10:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-02 10:00:00',
        updatedTime: '2024-01-15 14:10:00'
      },
      {
        id: 'SPCC1752154718337005',
        providerId: 'SP1752154718337',
        channelId: 'CH0004',
        channelName: '斗拱支付',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'DG9876543210'
          },
          security: {
            apiKey: 'dg_api_key_987654321098765432109876',
            secretKey: 'dg_secret_key_987654321098765432109876'
          },
          advanced: {
            notifyUrl: 'https://api.tianyuan.com/notify/dougong',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-13 17:25:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-02 10:00:00',
        updatedTime: '2024-01-13 17:25:00'
      },
      {
        id: 'SPCC1752154718337006',
        providerId: 'SP1752154718337',
        channelId: 'CH0006',
        channelName: '拉卡拉',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'LKL9876543210'
          },
          security: {
            apiKey: 'lkl_api_key_987654321098765432109876',
            secretKey: 'lkl_secret_key_987654321098765432109876'
          },
          advanced: {
            notifyUrl: 'https://api.tianyuan.com/notify/lakala',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-14 19:40:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-02 10:00:00',
        updatedTime: '2024-01-14 19:40:00'
      },
      {
        id: 'SPCC1752154718337007',
        providerId: 'SP1752154718337',
        channelId: 'CH0007',
        channelName: '乐刷支付',
        enabled: false,
        configData: {
          basic: {
            merchantId: 'LS9876543210'
          },
          security: {
            apiKey: '',
            secretKey: ''
          },
          advanced: {
            notifyUrl: '',
            sandboxMode: 'false'
          }
        },
        status: 'INACTIVE',
        createdTime: '2024-01-02 10:00:00',
        updatedTime: '2024-01-02 10:00:00'
      }
    ],
    status: 1,
    createdTime: '2024-01-02 10:00:00'
  },
  {
    id: 3,
    providerId: 'SP1752154718338',
    providerName: '蓝图引擎服务商',
    providerType: 'TECH',
    contactPerson: '王五',
    contactPhone: '13700137000',
    contactEmail: 'wangwu@shouyin.com',
    merchantCount: 45,
    channelConfigs: [
      {
        id: 'SPCC1752154718338001',
        providerId: 'SP1752154718338',
        channelId: 'CH0001',
        channelName: '微信支付',
        enabled: true,
        configData: {
          basic: {
            appId: 'wx5555666677778888',
            mchId: '5555666677',
            apiKey: 'abcdefghijk123456789lmnopqrstuvw',
            apiVersion: 'v3'
          },
          advanced: {
            notifyUrl: 'https://api.lantu.com/notify/wechat',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-13 16:20:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-03 10:00:00',
        updatedTime: '2024-01-13 16:20:00'
      },
      {
        id: 'SPCC1752154718338002',
        providerId: 'SP1752154718338',
        channelId: 'CH0002',
        channelName: '支付宝',
        enabled: true,
        configData: {
          basic: {
            appId: '2021001555566666',
            pid: '2088555566667777',
            signType: 'RSA2'
          },
          security: {
            privateKey: '-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA5a8bcdefghijklmnopqrstuv...',
            publicKey: '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...'
          },
          advanced: {
            notifyUrl: 'https://api.lantu.com/notify/alipay',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-14 10:15:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-03 10:00:00',
        updatedTime: '2024-01-14 10:15:00'
      },
      {
        id: 'SPCC1752154718338003',
        providerId: 'SP1752154718338',
        channelId: 'CH0004',
        channelName: '斗拱支付',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'DG5555666677'
          },
          security: {
            apiKey: 'dg_api_key_555566667777888899990000',
            secretKey: 'dg_secret_key_555566667777888899990000'
          },
          advanced: {
            notifyUrl: 'https://api.lantu.com/notify/dougong',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-12 14:15:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-03 10:00:00',
        updatedTime: '2024-01-12 14:15:00'
      },
      {
        id: 'SPCC1752154718338004',
        providerId: 'SP1752154718338',
        channelId: 'CH0003',
        channelName: '汇付天下',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'HF5555666677'
          },
          security: {
            apiKey: 'hf_api_key_555566667777888899990000',
            secretKey: 'hf_secret_key_555566667777888899990000'
          },
          advanced: {
            notifyUrl: 'https://api.lantu.com/notify/huifu',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-15 08:30:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-03 10:00:00',
        updatedTime: '2024-01-15 08:30:00'
      },
      {
        id: 'SPCC1752154718338005',
        providerId: 'SP1752154718338',
        channelId: 'CH0005',
        channelName: '富友支付',
        enabled: false,
        configData: {
          basic: {
            merchantId: 'FY5555666677'
          },
          security: {
            apiKey: '',
            secretKey: ''
          },
          advanced: {
            notifyUrl: '',
            sandboxMode: 'false'
          }
        },
        status: 'INACTIVE',
        createdTime: '2024-01-03 10:00:00',
        updatedTime: '2024-01-03 10:00:00'
      },
      {
        id: 'SPCC1752154718338006',
        providerId: 'SP1752154718338',
        channelId: 'CH0006',
        channelName: '拉卡拉',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'LKL5555666677'
          },
          security: {
            apiKey: 'lkl_api_key_555566667777888899990000',
            secretKey: 'lkl_secret_key_555566667777888899990000'
          },
          advanced: {
            notifyUrl: 'https://api.lantu.com/notify/lakala',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-15 12:15:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-03 10:00:00',
        updatedTime: '2024-01-15 12:15:00'
      },
      {
        id: 'SPCC1752154718338007',
        providerId: 'SP1752154718338',
        channelId: 'CH0007',
        channelName: '乐刷支付',
        enabled: true,
        configData: {
          basic: {
            merchantId: 'LS5555666677'
          },
          security: {
            apiKey: 'ls_api_key_555566667777888899990000',
            secretKey: 'ls_secret_key_555566667777888899990000'
          },
          advanced: {
            notifyUrl: 'https://api.lantu.com/notify/leshua',
            sandboxMode: 'false'
          }
        },
        status: 'ACTIVE',
        lastTestTime: '2024-01-14 18:45:00',
        lastTestResult: 'SUCCESS',
        createdTime: '2024-01-03 10:00:00',
        updatedTime: '2024-01-14 18:45:00'
      }
    ],
    status: 1,
    createdTime: '2024-01-03 10:00:00'
  }
]

export const mockLoadProviders = (params: any) => {
  const { current = 1, pageSize = 10, providerName, providerType, status } = params

  let filteredData = serviceProviders

  if (providerName) {
    filteredData = filteredData.filter((p) => p.providerName.includes(providerName))
  }
  if (providerType) {
    filteredData = filteredData.filter((p) => p.providerType === providerType)
  }
  if (status !== undefined && status !== null) {
    filteredData = filteredData.filter((p) => p.status === Number(status))
  }

  const total = filteredData.length
  const start = (current - 1) * pageSize
  const end = start + pageSize
  const paginatedData = filteredData.slice(start, end)

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: paginatedData,
        total: total
      })
    }, 500)
  })
}

// 获取服务商渠道配置
export const mockGetProviderChannelConfigs = (providerId: string) => {
  const provider = serviceProviders.find(p => p.providerId === providerId)
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: provider?.channelConfigs || []
      })
    }, 300)
  })
}

// 保存服务商渠道配置
export const mockSaveProviderChannelConfig = (config: ServiceProviderChannelConfig) => {
  const provider = serviceProviders.find(p => p.providerId === config.providerId)
  if (provider) {
    const existingIndex = provider.channelConfigs.findIndex(c => c.channelId === config.channelId)
    if (existingIndex >= 0) {
      provider.channelConfigs[existingIndex] = { ...config, updatedTime: new Date().toLocaleString() }
    } else {
      provider.channelConfigs.push({ ...config, createdTime: new Date().toLocaleString(), updatedTime: new Date().toLocaleString() })
    }
  }

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        success: true,
        message: '保存成功'
      })
    }, 500)
  })
}

// 测试渠道连接
export const mockTestChannelConnection = (providerId: string, channelId: string) => {
  // 模拟测试结果：80% 成功率
  const isSuccess = Math.random() > 0.2

  return new Promise((resolve) => {
    setTimeout(() => {
      if (isSuccess) {
        resolve({
          success: true,
          message: '连接测试成功',
          result: 'SUCCESS'
        })
      } else {
        resolve({
          success: false,
          message: '连接测试失败：网络超时或配置错误',
          result: 'FAILED'
        })
      }
    }, 2000) // 模拟测试需要2秒
  })
}

// 批量更新渠道状态
export const mockBatchUpdateChannelStatus = (providerId: string, updates: { channelId: string; enabled: boolean }[]) => {
  const provider = serviceProviders.find(p => p.providerId === providerId)
  if (provider) {
    updates.forEach(update => {
      const config = provider.channelConfigs.find(c => c.channelId === update.channelId)
      if (config) {
        config.enabled = update.enabled
        config.status = update.enabled ? 'ACTIVE' : 'INACTIVE'
        config.updatedTime = new Date().toLocaleString()
      }
    })
  }

  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        success: true,
        message: '批量更新成功'
      })
    }, 800)
  })
}

// 基于协议的配置生成函数
export const generateChannelConfigByProtocol = (channelCode: string, providerId: string): ServiceProviderChannelConfig => {
  // 使用约定方式获取协议ID，然后获取协议配置
  const protocolId = protocol3Manager.getProtocolByConvention(channelCode, 'MERCHANT_CHANNEL_CONFIG_V3')
  const protocol = protocol3Manager.getProtocol(protocolId)
  if (!protocol) {
    throw new Error(`找不到渠道 ${channelCode} 的协议配置`)
  }
  const defaultConfig = {} // 使用空对象作为默认配置

  return {
    id: `SPCC${providerId}${Date.now()}`,
    providerId,
    channelId: paymentChannels.find(c => c.channelCode === channelCode)?.channelId || channelCode,
    channelName: protocol.channelName,
    enabled: false,
    configData: defaultConfig,
    status: 'INACTIVE',
    createdTime: new Date().toLocaleString(),
    updatedTime: new Date().toLocaleString()
  }
}

// 获取所有可配置的渠道（基于协议）
export const getAllConfigurableChannels = () => {
  const configurableChannels = []

  for (const channel of paymentChannels) {
    try {
      // 使用约定方式获取协议ID，然后获取协议配置
      const protocolId = protocol3Manager.getProtocolByConvention(channel.channelCode, 'MERCHANT_CHANNEL_CONFIG_V3')
      const protocol = protocol3Manager.getProtocol(protocolId)
      if (!protocol) continue
      const result = { protocol, isDefault: false }
      configurableChannels.push({
        channelId: channel.channelId,
        channelCode: channel.channelCode,
        channelName: channel.channelName,
        iconUrl: channel.iconUrl,
        protocol: result.protocol,
        protocolVersion: result.protocol.version,
        isDefault: result.isDefault,
        description: result.protocol.description
      })
    } catch (error) {
      console.warn(`渠道 ${channel.channelName} (${channel.channelCode}) 协议解析失败:`, error.message)
      // 继续处理其他渠道，不中断整个过程
    }
  }

  return configurableChannels
}

// 验证渠道配置数据
export const validateChannelConfigData = (channelCode: string, configData: Record<string, any>) => {
  // 使用约定方式获取协议ID，然后获取协议配置
  const protocolId = protocol3Manager.getProtocolByConvention(channelCode, 'MERCHANT_CHANNEL_CONFIG_V3')
  const protocol = protocol3Manager.getProtocol(protocolId)
  if (!protocol) {
    return { valid: false, errors: [`找不到渠道 ${channelCode} 的协议配置`] }
  }
  const errors: string[] = []

  // 验证必填字段
  for (const field of protocol.configFields) {
    if (field.required && (!configData[field.fieldKey] || configData[field.fieldKey] === '')) {
      errors.push(`${field.fieldName}是必填项`)
    }

    // 验证字段格式
    if (field.validation && configData[field.fieldKey]) {
      const value = configData[field.fieldKey]
      const validation = field.validation

      if (validation.pattern && !new RegExp(validation.pattern).test(value)) {
        errors.push(validation.message || `${field.fieldName}格式不正确`)
      }

      if (validation.minLength && value.length < validation.minLength) {
        errors.push(`${field.fieldName}长度不能少于${validation.minLength}位`)
      }

      if (validation.maxLength && value.length > validation.maxLength) {
        errors.push(`${field.fieldName}长度不能超过${validation.maxLength}位`)
      }
    }
  }

  return {
    valid: errors.length === 0,
    errors
  }
}